package com.sdhs.util.daoru;

import com.sdhs.common.annotation.Log;
import com.sdhs.common.core.domain.AjaxResult;
import com.sdhs.common.enums.BusinessType;
import com.sdhs.common.utils.poi.ExcelUtil;
import com.sdhs.common.utils.spring.SpringUtils;
import com.sdhs.costcontrol.domain.GcControlContractPay;
import com.sdhs.costcontrol.service.IGcControlContractPayService;
import com.sdhs.myproject.domain.GcMyprojectContractInformation;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.domain.GcMyprojectProfitMarginMeasurement;
import com.sdhs.myproject.service.IGcMyprojectContractInformationService;
import com.sdhs.myproject.service.IGcMyprojectInformationService;
import com.sdhs.myproject.service.IGcMyprojectProfitMarginMeasurementService;
import com.sdhs.projectschedule.domain.GcProgressPaymentCollectionFill;
import com.sdhs.projectschedule.domain.GcProgressPaymentCollectionTracking;
import com.sdhs.projectschedule.service.IGcProgressPaymentCollectionFillService;
import com.sdhs.projectschedule.service.IGcProgressPaymentCollectionTrackingService;
import com.sdhs.projectstart.domain.ProjectDept;
import com.sdhs.projectstart.service.IProjectDeptService;
import com.sdhs.system.domain.GcContract;
import com.sdhs.system.domain.GcContractParty;
import com.sdhs.system.service.IGcContractService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/import")
public class importDataUtil {
    /*合同service*/
    private static final IGcContractService gcContractService = SpringUtils.getBean(IGcContractService.class);
    /*我的项目service*/
    private static final IGcMyprojectInformationService projectInformationService = SpringUtils.getBean(IGcMyprojectInformationService.class);
    /*我的项目-利润率测算service*/
    private static final IGcMyprojectProfitMarginMeasurementService projectProfitMarginMeasurementService = SpringUtils.getBean(IGcMyprojectProfitMarginMeasurementService.class);
    /*我的项目-合同信息service*/
    private static final IGcMyprojectContractInformationService projectContractInformationService = SpringUtils.getBean(IGcMyprojectContractInformationService.class);
    /*项目启动-新项目部组件*/
    private static final IProjectDeptService projectDeptService = SpringUtils.getBean(IProjectDeptService.class);
    /*回款跟踪*/
    private static final IGcProgressPaymentCollectionTrackingService progressPaymentCollectionTrackingService = SpringUtils.getBean(IGcProgressPaymentCollectionTrackingService.class);
    /*回款跟踪子-回款填报*/
    private static final IGcProgressPaymentCollectionFillService progressPaymentCollectionFillService = SpringUtils.getBean(IGcProgressPaymentCollectionFillService.class);
    /*支付跟踪*/
    private static final IGcControlContractPayService controlContractPayService = SpringUtils.getBean(IGcControlContractPayService.class);

    @Log(title = "导入清单管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<importData> util = new ExcelUtil<>(importData.class);
        List<importData> importDataList = util.importExcel(file.getInputStream(),1);

        for(importData importData : importDataList){
            /**处理导入合同的数据开始*/
            GcContract gcContract = new GcContract();
            GcContract existingContract = gcContractService.selectGcContractByContractId(importData.getContractId());
            gcContract.setContractId(importData.getContractId()); //合同编号
            gcContract.setName(importData.getName()); //合同名称
            gcContract.setNum(importData.getNum());//合同编号
            gcContract.setMainType(importData.getMainType());//合同业务类型
            gcContract.setIncomeExpenseType(importData.getIncomeExpenseType());//合同收支类型
            gcContract.setContractManager(importData.getContractManager());//合同负责人
            gcContract.setCompanyName(importData.getCompanyName());//合同归属单位
            gcContract.setCompanyId(importData.getCompanyId());//合同归属单位Id
            gcContract.setMoney(importData.getMoney());//合同总金额（含税）
            gcContract.setNotMoney(importData.getNotMoney());//合同总金额（不含税）
            gcContract.setChangeMoney(importData.getChangeMoney());//合同变更后总金额（含税）
            gcContract.setNotChangeMoney(importData.getNotChangeMoney());//合同变更后总金额（不含税）
            gcContract.setTaxRate(importData.getTaxRate());//税率
            gcContract.setTaxAmount(importData.getTaxAmount());//税额
            gcContract.setSignDate(importData.getSignDate());//合同签订日期
            /*gcContract.setIsSupplementaryContract(importData.getIsSupplementaryContract());*/
            gcContract.setOriginalContractNum(importData.getOriginalContractNum()); //补充合同所属原合同主数据编码
            String originalContractNum = importData.getIsSupplementaryContract(); //是否补充合同
            if ("是".equals(originalContractNum)) {
                gcContract.setIsSupplementaryContract("1");
            } else if ("否".equals(originalContractNum)) {
                gcContract.setIsSupplementaryContract("0");
            } else {
                gcContract.setIsSupplementaryContract("0");
            }
            String participantsNamesStr = importData.getParticipantsName(); //签约对方单位
            String participantsCodesStr = importData.getParticipantsCode();  //签约对方单位CODE
            String[] names = participantsNamesStr.split(",");
            String[] codes = participantsCodesStr.split(",");
            if (names.length != codes.length) {
                throw new IllegalArgumentException("签约对方单位名称和编码数量不一致");
            }
            ArrayList<GcContractParty> participants = new ArrayList<>();
            for (int i = 0; i < names.length; i++) {
                GcContractParty party = new GcContractParty();
                party.setParticipantsName(names[i].trim());    // 签约对方单位名称
                party.setParticipantsCode(codes[i].trim());
                participants.add(party);
            }
            gcContract.setParticipants(participants);//合同对方单位Id
            if (existingContract == null) {
                 gcContractService.insertGcContract(gcContract);
            } else {
                gcContractService.updateGcContract(gcContract);
            }
            /** 处理导入合同的数据结束*/

            /** 项目数据开始*/
            /*根据项目编号查询项目信息*/
             GcMyprojectInformation gcMyprojectInformation = projectInformationService.selectProjectInformationByNumber(importData.getProjectNumber());
            GcMyprojectInformation myProjectInformation = new GcMyprojectInformation();
             if(gcMyprojectInformation == null){
                 myProjectInformation.setProjectNumber(importData.getProjectNumber()); //项目编号
                 myProjectInformation.setProjectName(importData.getProjectName()); //项目名称
                 myProjectInformation.setProjectStatus(importData.getProjectStatus()); //项目状态
                 myProjectInformation.setCreater(importData.getManager()); //项目经理
                 myProjectInformation.setProjectData(importData.getSignDate().substring(0,4)); //项目所属年份
                 myProjectInformation.setOrganization(importData.getCompanyId()); //项目所属单位
                if("服务类合同".equals(importData.getMainType()) || "投资类合同".equals(importData.getMainType())){
                    myProjectInformation.setProjectType("3"); //项目类型-技术服务类
                } else if ("物资类合同".equals(importData.getMainType()) || "装备（设备）类合同".equals(importData.getMainType())) {
                    myProjectInformation.setProjectType("1"); //项目类型-设备采购类
                }else if ("工程类合同".equals(importData.getMainType()) ){
                    myProjectInformation.setProjectType("2"); //项目类型-集成施工类
                }


                 myProjectInformation.setIsFocus("yes");//是否重点项目- 是
                 /*如果是收入类的话将相对方数据赋值给业主单位*/
                 if("收入类".equals(importData.getIncomeExpenseType())){
                     myProjectInformation.setOwnerUnit(importData.getParticipantsName()); //业主单位
                 }
                 projectInformationService.insertGcMyprojectInformation(myProjectInformation);
                 /**处理 我的项目-利润率测算新增方法*/
                 GcMyprojectProfitMarginMeasurement myProjectProfitMarginMeasurement = new GcMyprojectProfitMarginMeasurement();
                 myProjectProfitMarginMeasurement.setIsAdvancefund("no");//是否垫资-否
                 myProjectProfitMarginMeasurement.setProjectId(myProjectInformation.getId()); //项目id
                 myProjectProfitMarginMeasurement.setOverheadCostCap(BigDecimal.ZERO); //管理成本上限
                 projectProfitMarginMeasurementService.insertGcMyprojectProfitMarginMeasurement(myProjectProfitMarginMeasurement);
                 ProjectDept projectDept = new ProjectDept();
                 if(gcMyprojectInformation==null){
                     projectDept.setProjectId(myProjectInformation.getId()); //项目id
                 }else {
                     projectDept.setProjectId(gcMyprojectInformation.getId()); //项目id
                 }
                 projectDept.setManager(importData.getManager());//项目经理
                 projectDept.setApprovalStatus("2");//审批状态-已通过
                 projectDeptService.insertProjectDept(projectDept);
             }else if("收入类".equals(importData.getIncomeExpenseType())){
                 gcMyprojectInformation.setOwnerUnit(importData.getParticipantsName()); //业主单位
                 projectInformationService.updateGcMyProject(gcMyprojectInformation);
             }
            /**处理我的项目-合同数据开始*/

            GcMyprojectContractInformation contractInformation = new GcMyprojectContractInformation();
            if(gcMyprojectInformation==null){
                contractInformation.setProjectId(myProjectInformation.getId()); //项目id
            }else {
                contractInformation.setProjectId(gcMyprojectInformation.getId()); //项目id
            }
            contractInformation.setContractId(importData.getContractId()); //合同编号
            contractInformation.setInvoicedAmount(importData.getInvoicedAmount());//已开票金额（含税）
            contractInformation.setNotInvoicedAmount(importData.getNotInvoicedAmount());//已开票金额（不含税）
            contractInformation.setProportionInvoicedMounts(importData.getProportionInvoicedMounts());//已开票比例
            contractInformation.setUninvoicedAmount(importData.getUninvoicedAmount());//未开票金额（含税）
            contractInformation.setProportionUnissuedInvoices(importData.getProportionUnissuedInvoices());//未开票比例
            contractInformation.setAmountRevenueRecognized(importData.getAmountRevenueRecognized());//收入确认金额(收入类合同)
            contractInformation.setRevenueRecognitionRatio(importData.getRevenueRecognitionRatio());//收入确认比例(收入类合同)
            contractInformation.setAmountAlreadyReceived(importData.getAmountAlreadyReceived());//已收款金额(收入类合同)
            contractInformation.setProportionPaymentsReceived(importData.getProportionPaymentsReceived());//已收款比例(收入类合同)
            contractInformation.setAccountsReceivable(importData.getAccountsReceivable());//应收账款金额(收入类合同)
            contractInformation.setContractAssets(importData.getContractAssets());//合同资产金额(收入类合同)
            contractInformation.setCostConfirmationAmount(importData.getCostConfirmationAmount());//成本确认金额(收入类合同)
            contractInformation.setCostConfirmationRatio(importData.getCostConfirmationRatio());//成本确认比例(收入类合同)
            contractInformation.setAmountPaid(importData.getAmountPaid());//已付款金额(收入类合同)
            contractInformation.setPercentagePaymentRatio(importData.getPercentagePaymentRatio());//已付款比例(收入类合同)
            contractInformation.setAccountsPayable(importData.getAccountsPayable());//应付账款金额(收入类合同)
            projectContractInformationService.insertGcMyprojectContractInformation(contractInformation);
            /**处理我的项目-合同数据结束*/

            /**项目数据结束*/
            /**处理回款填报和支付跟踪数据开始*/

            if("收入类".equals(importData.getIncomeExpenseType())){
                /*回款跟踪*/
                GcProgressPaymentCollectionTracking gcProgressPaymentCollectionTracking = new GcProgressPaymentCollectionTracking();
                if(gcMyprojectInformation==null){
                    gcProgressPaymentCollectionTracking.setProjectId(myProjectInformation.getId()); //项目id
                }else {
                    gcProgressPaymentCollectionTracking.setProjectId(gcMyprojectInformation.getId()); //项目id
                }
                gcProgressPaymentCollectionTracking.setContractNode(importData.getProjectName()+"合同节点"); //合同节点
                gcProgressPaymentCollectionTracking.setFinishTime(new Date()); //预计完成时间
                gcProgressPaymentCollectionTracking.setPlannedRepaymentProportion(importData.getProportionPaymentsReceived()); //计划回款比例
                gcProgressPaymentCollectionTracking.setPaidBackMoney(importData.getAmountAlreadyReceived());//计划已回款金额
                gcProgressPaymentCollectionTracking.setContractId(importData.getContractId());//合同id
                /*调用回款跟踪主接口*/
                progressPaymentCollectionTrackingService.insertGcProgressPaymentCollectionTracking(gcProgressPaymentCollectionTracking);
                /*回款跟踪子-回款填报*/
                GcProgressPaymentCollectionFill gcProgressPaymentCollectionFill = new GcProgressPaymentCollectionFill();
                if(gcMyprojectInformation==null){
                    gcProgressPaymentCollectionFill.setProjectId(myProjectInformation.getId()); //项目id
                }else {
                    gcProgressPaymentCollectionFill.setProjectId(gcMyprojectInformation.getId()); //项目id
                }
                gcProgressPaymentCollectionFill.setContractId(importData.getContractId());//合同id
                gcProgressPaymentCollectionFill.setFillTime(new Date()); //填报时间
                gcProgressPaymentCollectionFill.setBillingTime(new Date()); //开票时间
                gcProgressPaymentCollectionFill.setPaidBack(importData.getAmountAlreadyReceived()); //本次回款（元）
                gcProgressPaymentCollectionFill.setPaidBackProportion(importData.getProportionPaymentsReceived()); //本次回款比例
                gcProgressPaymentCollectionFill.setInvoicedOut(importData.getInvoicedAmount());//本次开票（元）
                gcProgressPaymentCollectionFill.setInvoicedOutProportion(importData.getProportionInvoicedMounts());//本次开票比例
                gcProgressPaymentCollectionFill.setNotInvoicedAmount(importData.getNotInvoicedAmount());//已开票金额（不含税）
                gcProgressPaymentCollectionFill.setUninvoicedAmount(importData.getUninvoicedAmount());//未开票金额（含税）
                gcProgressPaymentCollectionFill.setProportionUnissuedInvoices(importData.getProportionUnissuedInvoices());//未开票比例(含税)
                gcProgressPaymentCollectionFill.setAmountRevenueRecognized(importData.getAmountRevenueRecognized());//收入确认金额（收入类合同）
                gcProgressPaymentCollectionFill.setRevenueRecognitionRatio(importData.getRevenueRecognitionRatio());//收入确认比例(收入类合同)
                gcProgressPaymentCollectionFill.setAccountsReceivable(importData.getAccountsReceivable());//应收账款金额（收入类合同）
                gcProgressPaymentCollectionFill.setContractAssets(importData.getContractAssets());//合同资产金额（收入类合同）
                gcProgressPaymentCollectionFill.setNotAmountRevenueRecognized(importData.getNotAmountRevenueRecognized());//收入确认金额（不含税）
                progressPaymentCollectionFillService.insertGcProgressPaymentCollectionFill(gcProgressPaymentCollectionFill);
            } else if ("支出类".equals(importData.getIncomeExpenseType())) {
                /*支付跟踪*/
                GcControlContractPay gcControlContractPay = new GcControlContractPay();
                if(gcMyprojectInformation==null){
                    gcControlContractPay.setProjectId(myProjectInformation.getId()); //项目id
                }else {
                    gcControlContractPay.setProjectId(gcMyprojectInformation.getId()); //项目id
                }
                gcControlContractPay.setContractId(importData.getContractId()); //合同编号
                gcControlContractPay.setFillingDate(new Date()); //填报日期
                gcControlContractPay.setPaymentDate(new Date()); //支付日期
                gcControlContractPay.setThisPaymentAmount(importData.getAmountPaid()); //本次支付金额
                gcControlContractPay.setThisPaymentRatio(importData.getPercentagePaymentRatio()); //本次支付比例
                gcControlContractPay.setThisInvoiceAmount(importData.getInvoicedAmount());//本次发票金额
                gcControlContractPay.setThisInvoiceRatio(importData.getProportionInvoicedMounts());//本次发票比例
                gcControlContractPay.setNotInvoicedAmount(importData.getNotInvoicedAmount());//已开票金额（不含税）
                gcControlContractPay.setUninvoicedAmount(importData.getUninvoicedAmount());//未开票金额（含税）
                gcControlContractPay.setProportionUnissuedInvoices(importData.getProportionUnissuedInvoices());//未开票比例(含税)
                gcControlContractPay.setCostConfirmationAmount(importData.getCostConfirmationAmount());//成本确认金额(支出类合同)
                gcControlContractPay.setCostConfirmationRatio(importData.getCostConfirmationRatio());//成本确认比例(支出类合同)
                gcControlContractPay.setAccountsPayable(importData.getAccountsPayable());//应付账款(支出类合同)
                gcControlContractPay.setNotCostConfirmationAmount(importData.getNotCostConfirmationAmount());//成本确认金额(支出类合同)
                controlContractPayService.insertGcControlContractPay(gcControlContractPay);
            }
            /**处理回款填报和支付跟踪数据结束*/
        }

        return AjaxResult.success();
    }

}